from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from .models import *
import re
import datetime
class CodeSer(serializers.ModelSerializer):
    class Meta:
        model=Code
        fields=['phone']
    def validate_phone(self, phone):
        if not re.match("^1[3578]\d{9}$",phone):
            raise ValidationError("手机号格式错误")
        cobj=Code.objects.filter(phone=phone).order_by("-created").first()

        if cobj and datetime.datetime.now() < cobj.created+datetime.timedelta(minutes=1):
            raise ValidationError("短信发送间隔小于1分钟")
        return phone

class UserSer(serializers.ModelSerializer):
    code=serializers.CharField(max_length=6)
    class Meta:
        model=User
        fields=['username','password','phone','age','code']
    def validate(self, attrs):
        phone=attrs.get("phone")
        code=attrs.get("code")
        cobj=Code.objects.filter(phone=phone).order_by("-created").first()
        if User.objects.filter(phone=phone):
            raise ValidationError("手机号已被注册")

        if code!=cobj.code:
            raise ValidationError("验证码错误")

        if not cobj:
            raise ValidationError("手机没有收到验证码")

        if datetime.datetime.now() > cobj.created+datetime.timedelta(seconds=90):
            raise ValidationError("验证码超时")

        return attrs

    def create(self, validated_data):
        del validated_data['code']
        return User.objects.create_user(**validated_data)

class BookSer(serializers.ModelSerializer):
    class Meta:
        model=Book
        fields="__all__"
    type=serializers.SlugRelatedField(queryset=Type.objects.all(),slug_field='type')